import React, { Component } from 'react';
import { getMultiLang, createPage, cardCache, toast, viewModel, promptBox } from 'nc-lightapp-front';
import _ from 'lodash-es';
import config from './config';
import {
    onSearchButtonClick,
    onPageButtonClick,
    onTablePageChange,
    onTableInnerButtonClick,
    onTableSelectChange,
    onTableRowDoubleClick
} from './events';
import api from '../../common/api';

const { setDefData, getDefData } = cardCache;

class Page extends Component {
    constructor(props) {
        super(props);
        props.use.search(config.searchcode);
        props.use.form(config.headcode);
        props.use.table(config.bodycode);
        this.state = {
            multiLang: {},
            tradeType: '',
            tradeTypeName: ''
        };
        // TODO 缓存多语
    }

    componentDidMount() {
        this.initTempAndLang();
    }

    initTempAndLang() {
        const props = this.props;
        getMultiLang({
            ...config.multiLang,
            callback: json => {
                this.setState({ multiLang: json }, () => {
                    props.createUIDom({ pagecode: config.pagecode }, data => {
                        console.log('=====template', data);
                        this.setButton(data.button);
                        this.setMeta(data.template, data);
                    });
                });
            }
        });
    }

    setMeta(meta, all) {
        const props = this.props;

        meta[config.headcode].items.forEach(item => {
            if (item.attrcode === 'pk_tradetypeid') {
                item.queryCondition = function () {
                    return {
                        GridRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.ErmTranstypeRefSqlBuilder'
                    };
                };
            } else if (item.attrcode === 'pk_org') {
                item.queryCondition = function () {
                    return {
                        TreeRefActionExt: 'nccloud.web.erm.action.ref.sqlbuilder.OrgTreeRefSqlBuilder',
                        DataPowerOperationCode: 'fi',
                        isDataPowerEnable: 'Y'
                    };
                };
            }
        });

        meta[config.bodycode].pagination = true;
        meta[config.bodycode].pageInfo = {
            pageSize: config.pageSize
        };

        const tableInnerButtons = props.button
            .getButtons()
            .filter(item => item.area === config.innerButtonArea)
            .map(item => item.key);

        meta[config.bodycode].items.push({
            label: this.state.multiLang['opr_title'],
            itemtype: 'customer',
            attrcode: 'opr',
            width: '140px',
            visible: true,
            fixed: 'right',
            render: (text, record, index) => {
                return props.button.createOprationButton(tableInnerButtons, {
                    area: config.innerButtonArea,
                    buttonLimit: 5,
                    onButtonClick: (props, key) => {
                        onTableInnerButtonClick.call(this, props, key, text, record, index);
                    }
                });
            }
        });
        props.meta.setMeta(meta, () => {
            this.initPage();
        });
    }

    setButton(button) {
        const props = this.props;
        props.button.setButtons(button);

        props.button.setPopContent({
            table_inner_submit: this.state.multiLang['confirm_submit_select'],
            table_inner_retrieve: this.state.multiLang['confirm_retrieve_select'],
            table_inner_delete: this.state.multiLang['confirm_delete_select']
        });
    }

    initPage() {
        const props = this.props;
        props.table.setTableRender(config.bodycode, 'djbh', (text, record) => {
            return (
                <a
                    // className="hyperlinks"
                    onClick={() => {
                        api.getBillLinkInfo({
                            openbillid: _.get(record, 'pk_jkbx.value'),
                            tradetype: _.get(record, 'djlxbm.value')
                        }).then(res => {
                            if (!res || !res.url) {
                                toast({
                                    color: 'warning',
                                    content: this.state.multiLang['bad_request']
                                }); /* 国际化处理： 参数错误*/
                                return;
                            }
                            props.specialOpenTo(res.url, {
                                status: 'browse',
                                id: res.openbillid,
                                tradetype: res.tradetype,
                                appcode: res.appcode,
                                pagecode: res.pagecode,
                                scene: 'bz'
                            });
                        });
                    }}
                >
                    {_.get(record, 'djbh.value')}
                </a>
            );
        });
        this.setPageStatus();

        // props.search.setSearchValByField(config.headcode, 'djrq', {
        //     value: '#week(0)#,#week(0)#'
        // });
    }

    setPageStatus() {
        const props = this.props;
        props.button.setButtonDisabled(['link', 'print', 'export'], true);
        props.table.selectAllRows(config.bodycode, false);
    }

    loadData(isFromSearch) {
        const props = this.props;
        const meta = props.meta.getMeta();
        const pageInfo = props.table.getTablePageInfo(config.bodycode);
        const query = props.search.getAllSearchData(config.searchcode);

        const params = {
            appcode: config.appcode,
            pagecode: config.pagecode,
            queryAreaCode: config.searchcode,
            querytype: 'tree',
            querycondition: query,
            oid: meta[config.searchcode].oid,
            tradetype: this.state.tradeType,
            pageInfo: {
                pageIndex: pageInfo.pageIndex,
                pageSize: isFromSearch ? config.pageSize : pageInfo.pageSize
            }
        };

        return api.getAuthorizationList(params).then(res => {
            // 按钮初始化
            if (isFromSearch) {
                const total = Number(_.get(res, 'pageInfo.total', 0));
                if (total === 0) {
                    toast({
                        color: 'warning',
                        content: this.state.multiLang['query_none_message']
                    }); /* 国际化处理： 未查询出符合条件的数据*/
                } else {
                    toast({
                        color: 'success',
                        content: this.state.multiLang['query_total_message'].replace('{count}', total)
                    }); /* 国际化处理： 查询成功，共*条*/
                }
            } else {
                toast({
                    color: 'success',
                    content: this.state.multiLang['query_success']
                }); /* 国际化处理： 查询成功*/
            }

            this.setData(res);
        });
    }

    setData(res) {
        const props = this.props;
        const pageInfo = _.get(res, `pageInfo`, {});
        const data = {
            rows: _.get(res, `data.body.${config.bodycode}.rows`, []),
            pageInfo: pageInfo
        };
        if (pageInfo.pageIndex == 0) {
            data.allpks = new Array(Number(pageInfo.total));
        }
        props.table.setAllTableData(config.bodycode, data);
        props.form.setAllFormValue({ [config.headcode]: _.get(res, `data.head[${config.headcode}]`) });
    }

    onDeleteItem(record, index) {
        const { table } = this.props;
        api.deleteAuthorizationItem({
            module: _.get(record, 'module.value', ''),
            userid: _.get(record, 'userid.value', ''),
            sysid: _.get(record, 'sysid.value', '')
        }).then(res => {
            table.deleteTableRowsByIndex(config.bodycode, index);
            toast({
                color: 'success',
                content: this.state.multiLang['delete_success']
            }); /* 国际化处理： 删除成功*/
        });
    }

    render() {
        const { table, button, search, form, BillHeadInfo } = this.props;
        const { NCCreateSearch } = search;
        const { createBillHeadInfo } = BillHeadInfo;
        const { createSimpleTable } = table;

        return (
            <div className="nc-single-table">
                <div className="nc-singleTable-header-area">
                    <div className="header-title-search-area">
                        {createBillHeadInfo({
                            title: this.state.multiLang['monitoring_page_title'],
                            initShowBackBtn: false
                        })}
                    </div>
                    <div className="header-button-area">
                        {button.createButtonApp({
                            area: config.pageButtonArea,
                            buttonLimit: 8,
                            onButtonClick: onPageButtonClick.bind(this)
                        })}
                    </div>
                </div>
                <div className="nc-singleTable-search-area">
                    {NCCreateSearch(config.searchcode, { clickSearchBtn: onSearchButtonClick.bind(this) })}
                    {form.createForm(config.headcode, {
                        // onAfterEvent: onTableAfterEvent.bind(this)
                        // onBeforeEvent: formBeforeEvent.bind(this)
                    })}
                </div>
                <div className="nc-singleTable-table-area">
                    {createSimpleTable(config.bodycode, {
                        onRowDoubleClick: onTableRowDoubleClick.bind(this),
                        handlePageInfoChange: onTablePageChange.bind(this),
                        selectedChange: onTableSelectChange.bind(this),
                        showIndex: true,
                        showCheck: true
                    })}
                </div>
            </div>
        );
    }
}

export default createPage({
    // billinfo: {
    //     billtype: 'grid',
    //     pagecode: config.pagecode,
    //     headcode: config.headcode
    // },
    mutiLangCode: config.mutiLangCode,
    initTemplate: null
})(Page);
